//
//  CYProjectDetail_XiangMuJieShaoViewController.m
//  cyydt
//
//  Created by chu on 2019/1/24.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYProjectDetail_XiangMuJieShaoViewController.h"
#import "CYProjectDetail_LikeCollectionViewCell.h"
#import "CYProjectDetail_LikeHeaderCollectionReusableView.h"
#import "ZFAVPlayerManager.h"
#import "ZFPlayerControlView.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "CYProjectDetail_JieShaoCollectionViewCell.h"
#import "CYProjectDetail_PhonePopView.h"
#import "CYProjectDetail_PhonePop1View.h"
#import "CYProjectDetailViewController.h"
@interface CYProjectDetail_XiangMuJieShaoViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, WKNavigationDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) UIView *playerContainerView;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) UIButton *playBtn;
@property (nonatomic, strong) CYProjectModel *detailModel;
@property (nonatomic, strong) CYProjectModel *videoModel;
@property (nonatomic, strong) UIImageView *coverImageView;

@property (nonatomic,strong) WKWebView *WKWebView;
@property (nonatomic, assign) CGFloat htmlCellHeight;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) CYProjectDetail_PhonePopView *ziliaoView;

@end

@implementation CYProjectDetail_XiangMuJieShaoViewController

- (void)dealloc{
    [self.WKWebView removeObserver:self forKeyPath:@"scrollView.contentSize"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.collectionView];
    
    if (self.model.mobile_url) {
        NSString *htmlUrl = [NSString stringWithFormat:@"%@&type=1", [self URLDecodedString:self.model.mobile_url]];
        [self.WKWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:htmlUrl] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10]];
    }
    
    
    [self getProjectVideo];
    [self getDetail];
    [self getDiCeng];

    [self.WKWebView addObserver:self forKeyPath:@"scrollView.contentSize" options:NSKeyValueObservingOptionNew context:nil];

}

// 键盘监听事件
- (void)keyboardAction:(NSNotification*)sender{
     // <注意>具有约束的控件通过改变约束值进行frame的改变处理
     if([sender.name isEqualToString:UIKeyboardWillShowNotification]){
         CGFloat x = 0;
         CGFloat y = 0;
         CGFloat w = CGRectGetWidth(self.view.frame);
         CGFloat h = 0;
         self.playerContainerView.frame = CGRectMake(x, y, w, h);
     }else{
         CGFloat x = 0;
         CGFloat y = 0;
         CGFloat w = CGRectGetWidth(self.view.frame);
         CGFloat h = w*9/16;
         self.playerContainerView.frame = CGRectMake(x, y, w, h);
     }
    
    self.collectionView.frame = CGRectMake(0, CGRectGetMaxY(self.playerContainerView.frame), kWindowW, kWindowH - Height_NavBar - 44 - self.playerContainerView.frame.size.height - self.bottomView.frame.size.height);
    
//    [self.collectionView reloadData];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{

    CGPoint p = [[change objectForKey:@"new"] CGPointValue];
    CGFloat height = p.y;
    
    if (self.htmlCellHeight == height) {
        
    }else{
        self.htmlCellHeight = height;
        self.WKWebView.frame = CGRectMake(0, 0, kWindowW, self.htmlCellHeight);
        [self.collectionView reloadData];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.videoModel) {
        if (indexPath.section == 2) {
            CYProjectDetailViewController *detail = [[CYProjectDetailViewController alloc] init];
            detail.model = self.dataSourceArr[indexPath.item];
            [[AppDelegate sharedAppDelegate] pushViewController:detail];
        }
    }else{
        if (indexPath.section == 1) {
            CYProjectDetailViewController *detail = [[CYProjectDetailViewController alloc] init];
            detail.model = self.dataSourceArr[indexPath.item];
            [[AppDelegate sharedAppDelegate] pushViewController:detail];
        }
    }
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.videoModel) {
        return 3;
    }
    return 2;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.videoModel) {
        if (section == 0 || section == 1) {
            return 1;
        }
        return self.dataSourceArr.count;
    }else{
        if (section == 0) {
            return 1;
        }
        return self.dataSourceArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.videoModel) {
        if (indexPath.section == 0) {
            
            CYProjectDetail_JieShaoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYProjectDetail_JieShaoCollectionViewCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[CYProjectDetail_JieShaoCollectionViewCell alloc] init];
            }
            cell.model = self.detailModel;
            __weak typeof(self)weakself = self;
            cell.openBlock = ^{
                if ([weakself.detailModel.isOpen boolValue]) {
                    weakself.detailModel.isOpen = [NSNumber numberWithBool:NO];
                }else{
                    weakself.detailModel.isOpen = [NSNumber numberWithBool:YES];
                }
                [weakself.collectionView reloadData];
            };
            cell.guanZhuBlock = ^{
                if ([weakself.detailModel.is_collect integerValue] == 1) {
                    [weakself cancleCollection];
                }else{
                    [weakself collection];
                }
            };
            return cell;
        }else if (indexPath.section == 1){
            UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[UICollectionViewCell alloc] init];
            }
            if (self.htmlCellHeight > 0) {
                [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                [cell.contentView addSubview:self.WKWebView];
            }
            return cell;
        }else {
            CYProjectDetail_LikeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYProjectDetail_LikeCollectionViewCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[CYProjectDetail_LikeCollectionViewCell alloc] init];
            }
            cell.model = self.dataSourceArr[indexPath.item];
            return cell;
        }
    }else{
        if (indexPath.section == 0){
            UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[UICollectionViewCell alloc] init];
            }
            if (self.htmlCellHeight > 0) {
                [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                [cell.contentView addSubview:self.WKWebView];
            }
            return cell;
        }else {
            CYProjectDetail_LikeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYProjectDetail_LikeCollectionViewCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[CYProjectDetail_LikeCollectionViewCell alloc] init];
            }
            cell.model = self.dataSourceArr[indexPath.item];
            return cell;
        }
    }
}

#pragma mark - 收藏取消收藏
- (void)cancleCollection{
    if (![YLUserInfo isLogIn]) {
        LoginViewController *login = [[LoginViewController alloc] init];
        [[AppDelegate sharedAppDelegate] pushViewController:login];
        return;
    }
    [EasyShowLodingView showLoding];
    __weak typeof(self)weakself = self;
    NSString *url = [NSString stringWithFormat:@"%@%@/%@",User_HOST, @"collection",self.detailModel.ID];
    NSDictionary *param = @{@"type":@"3", @"articleId":self.detailModel.ID};
    [[XBRequest sharedInstance] deleteDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"取消收藏 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                weakself.detailModel.is_collect = [NSNumber numberWithInteger:2];
                [weakself.collectionView reloadData];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                
            }
        }
    }];
}

- (void)collection{
    if (![YLUserInfo isLogIn]) {
        LoginViewController *login = [[LoginViewController alloc] init];
        [[AppDelegate sharedAppDelegate] pushViewController:login];
        return;
    }
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"collection/addCollect"];
    NSDictionary *param = @{@"type":@3, @"articleId":self.detailModel.ID};
    __weak typeof(self)weakself = self;
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"收藏本咨询 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                weakself.detailModel.is_collect = [NSNumber numberWithInteger:1];
                [weakself.collectionView reloadData];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                
            }
        }
    }];
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.videoModel) {
        if (indexPath.section == 0) {
            if ([self.detailModel.isOpen boolValue]) {
                CGFloat height = [[Tool sharedInstance] heightForString:self.detailModel.content andWidth:kWindowW - 30 fontSize:14];
                
                return CGSizeMake(kWindowW, 70 + height);
            }else{
                return CGSizeMake(kWindowW, 40);
                
            }
        }
        if (indexPath.section == 1) {
            return CGSizeMake(kWindowW, self.htmlCellHeight);
        }
        return CGSizeMake(kWindowW / 2, 60 + 110 * kWindowHOne);
    }else{
        if (indexPath.section == 0) {
            return CGSizeMake(kWindowW, self.htmlCellHeight);
        }
        return CGSizeMake(kWindowW / 2, 60 + 110 * kWindowHOne);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (self.videoModel) {
        if (section == 2) {
            return CGSizeMake(kWindowW, 45);
        }
        return CGSizeZero;
    }else{
        if (section == 1) {
            return CGSizeMake(kWindowW, 45);
        }
        return CGSizeZero;
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (self.videoModel) {
        if (section == 2) {
            //        return UIEdgeInsetsMake(20, 20, 20, 20);
        }
        return UIEdgeInsetsMake(0, 0, 10, 0);
    }else{
        if (section == 1) {
            //        return UIEdgeInsetsMake(20, 20, 20, 20);
        }
        return UIEdgeInsetsMake(0, 0, 10, 0);
    }

}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (self.videoModel) {
        UICollectionReusableView *view = nil;
        if (indexPath.section == 2) {
            if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
                view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CYProjectDetail_LikeHeaderCollectionReusableView" forIndexPath:indexPath];
                CYProjectDetail_LikeHeaderCollectionReusableView *footer = (CYProjectDetail_LikeHeaderCollectionReusableView *)view;
                
                return footer;
            }
        }
        return view;
    }else{
        UICollectionReusableView *view = nil;
        if (indexPath.section == 1) {
            if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
                view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CYProjectDetail_LikeHeaderCollectionReusableView" forIndexPath:indexPath];
                CYProjectDetail_LikeHeaderCollectionReusableView *footer = (CYProjectDetail_LikeHeaderCollectionReusableView *)view;
                
                return footer;
            }
        }
        return view;
    }
    
}


- (UICollectionView *)collectionView{
    if (!_collectionView) {
        //居左约束
        UICollectionViewFlowLayout *leftAlignedLayout = [[UICollectionViewFlowLayout alloc] init];
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowH - self.bottomView.frame.size.height - 44 - Height_NavBar) collectionViewLayout:leftAlignedLayout];
        _collectionView.backgroundColor = BackGroundColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectDetail_LikeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CYProjectDetail_LikeCollectionViewCell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectDetail_JieShaoCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CYProjectDetail_JieShaoCollectionViewCell"];

        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];

        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectDetail_LikeHeaderCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CYProjectDetail_LikeHeaderCollectionReusableView"];
        
    }
    return _collectionView;
}

- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        _controlView.autoHiddenTimeInterval = 5;
        _controlView.autoFadeTimeInterval = 0.5;
    }
    return _controlView;
}

- (UIView *)playerContainerView{
    if (!_playerContainerView) {
        _playerContainerView = [[UIView alloc] init];
        ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
        self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.playerContainerView];
//        self.player.WWANAutoPlay = YES;
        self.player.shouldAutoPlay = NO;
        self.player.controlView = self.controlView;
        
        /// 设置退到后台继续播放
        self.player.pauseWhenAppResignActive = NO;
        /// 播放完成
        __weak typeof(self)weakself = self;
        self.player.playerDidToEnd = ^(id  _Nonnull asset) {
            NSLog(@"======播放完毕了");
            //        [weakself.controlView resetControlView];
            weakself.controlView.portraitControlView.playOrPauseBtn.hidden = YES;
            [weakself.playBtn removeFromSuperview];
            [weakself.playerContainerView addSubview:weakself.playBtn];
        };
        self.player.playerReadyToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
            NSLog(@"======开始播放了");
            [weakself.coverImageView removeFromSuperview];
            [weakself.playBtn removeFromSuperview];
        };
        [self.playerContainerView addSubview:self.playBtn];
    }
    return _playerContainerView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.player.currentPlayerManager play];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    // 添加通知监听见键盘弹出/退出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.player.currentPlayerManager pause];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)playClick:(UIButton *)sender {
    self.controlView.portraitControlView.playOrPauseBtn.hidden = NO;
    [self.playBtn removeFromSuperview];
    self.player.assetURL = [NSURL URLWithString:self.videoModel.video_url];
}

- (void)addVideoView{
    if (self.videoModel) {
        CGFloat x = 0;
        CGFloat y = 0;
        CGFloat w = CGRectGetWidth(self.view.frame);
        CGFloat h = w*9/16;
        self.playerContainerView.frame = CGRectMake(x, y, w, h);
        
        w = 44;
        h = w;
        x = (CGRectGetWidth(self.playerContainerView.frame)-w)/2;
        y = (CGRectGetHeight(self.playerContainerView.frame)-h)/2;
        self.playBtn.frame = CGRectMake(x, y, w, h);
        
        [self.controlView showTitle:self.videoModel.title coverURLString:self.videoModel.cover_url fullScreenMode:ZFFullScreenModeAutomatic];
        [self.controlView.coverImageView sd_setImageWithURL:[NSURL URLWithString:self.videoModel.cover_url] placeholderImage:[UIImage imageNamed:@"videoPlaceHolde"]];
//        [self.playerContainerView addSubview:self.coverImageView];
//        [self.playerContainerView insertSubview:self.controlView belowSubview:self.coverImageView];
        [self.playBtn removeFromSuperview];
        [self.playerContainerView addSubview:self.playBtn];
        
        [self.view addSubview:self.playerContainerView];

        if ([[self getCurrentNetworkState] isEqualToString:@"WIFI"]) {
            //wifi
            
            [self playClick:nil];
        }else{
            [LEEAlert alert].config
            .LeeHeaderColor([UIColor whiteColor])
            .LeeAddContent(^(UILabel *label) {
                label.font = [UIFont systemFontOfSize:18];
                label.textColor = [UIColor blackColor];
                label.text = @"当前网络环境非WIFI状态,播放视频将消耗您的流量,是否继续播放?";
            }).LeeAddAction(^(LEEAction *action) {
                action.titleColor = RGBOF(0x666666);
                action.borderColor = RGBOF(0xE0DFDF);
                action.title = @"取消";
                
            })
            .LeeAddAction(^(LEEAction *action) {
                action.titleColor = RGBOF(0xF43636);
                action.borderColor = RGBOF(0xE0DFDF);
                action.title = @"确定";
                action.clickBlock = ^{
                    self.player.assetURL = [NSURL URLWithString:self.videoModel.video_url];

                };
            })
            .LeeShow();
        }
        
    }else{
        self.playerContainerView.frame = CGRectMake(0, 0, kWindowW, 0);
    }
    
    self.collectionView.frame = CGRectMake(0, CGRectGetMaxY(self.playerContainerView.frame), kWindowW, kWindowH - Height_NavBar - 44 - self.playerContainerView.frame.size.height - self.bottomView.frame.size.height);
}

- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:[UIImage imageNamed:@"video_pause"] forState:UIControlStateNormal];
        [_playBtn addTarget:self action:@selector(playClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (BOOL)shouldAutorotate {
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - WKWebViewDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    
//    __weak typeof(self)weakself = self;
//    [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
//        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
//        NSLog(@"heightStr --- %@",heightStr);
//        weakself.htmlCellHeight = [heightStr floatValue] + 15;
//        webView.frame = CGRectMake(0, 0, kWindowW, weakself.htmlCellHeight);
//        [weakself.collectionView reloadData];
//    }];
}

- (WKWebView *)WKWebView{
    if (!_WKWebView) {
        NSString *jScript =@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";
        
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];

        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        
        wkWebConfig.userContentController = wkUController;
        
        _WKWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 0) configuration:wkWebConfig];
        _WKWebView.navigationDelegate = self;
        _WKWebView.opaque = NO;
        _WKWebView.backgroundColor = [UIColor whiteColor];
        _WKWebView.scrollView.scrollEnabled = NO;
        
    }
    return _WKWebView;
}

#pragma mark - 获取项目的视频
- (void)getProjectVideo{
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"video/item-video"];
    NSDictionary *param = @{};
    if (self.isFromVideoDetail) {
        param = @{@"itemid":self.model.itemid};
    }else{
        param = @{@"itemid":self.model.ID};
    }
    __weak typeof(self)weakself = self;
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取项目视频 ---- %@",responseResult);
        if ([weakself.collectionView.mj_header isRefreshing]) {
            [weakself.collectionView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                
                if ([responseResult[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *data = responseResult[@"data"];
                    weakself.videoModel = [CYProjectModel mj_objectWithKeyValues:data];
                    [weakself addVideoView];
                }
            }else{
                
            }
        }
    }];
}
#pragma mark - 获取项目详情
- (void)getDetail{
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index/view"];
    NSDictionary *param = @{};
    if (self.isFromVideoDetail) {
        param = @{@"id":self.model.itemid, @"type":@"3"};
    }else{
        param = @{@"id":self.model.ID, @"type":@"3"};
    }
    __weak typeof(self)weakself = self;
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"项目详情 ---- %@",responseResult);
        if ([weakself.collectionView.mj_header isRefreshing]) {
            [weakself.collectionView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *data = responseResult[@"data"];
                    NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:data];
                    [muDic setObject:[NSNumber numberWithBool:NO] forKey:@"isOpen"];
                    weakself.detailModel = [CYProjectModel mj_objectWithKeyValues:muDic];
                    NSString *htmlUrl = [NSString stringWithFormat:@"%@&type=1", [weakself URLDecodedString:weakself.detailModel.mobile_url]];
                    [weakself.WKWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:htmlUrl] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10]];
                }
            }else{
                
            }
        }
    }];
}

-(NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}


#pragma mark - 获取底层
- (void)getDiCeng{
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"recommend"];
    NSDictionary *param = @{};
    if (self.isFromVideoDetail) {
        param = @{@"id":self.model.itemid, @"type":@"3"};
    }else{
        param = @{@"id":self.model.ID, @"type":@"3"};
    }
    __weak typeof(self)weakself = self;
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取底层项目 ---- %@",responseResult);
        if ([weakself.collectionView.mj_header isRefreshing]) {
            [weakself.collectionView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *data = responseResult[@"data"];
                    NSArray *hotBusiness = data[@"hotBusiness"];
                    [weakself.dataSourceArr removeAllObjects];
                    for (NSDictionary *dic in hotBusiness) {
                       CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                        [weakself.dataSourceArr addObject:model];
                    }
                    [weakself.collectionView reloadData];
                }
                
            }else{
                
            }
        }
    }];
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        if (HX_IS_IPhoneX_All) {
            _bottomView.frame = CGRectMake(0, kWindowH - Height_NavBar - 83 - 44, kWindowW, 83);
        }else{
            _bottomView.frame = CGRectMake(0, kWindowH - Height_NavBar - 48 - 44, kWindowW, 48);
        }
        
        UIView *contrainerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 48)];
        [_bottomView addSubview:contrainerView];
        
        NSArray *images = @[@"tonghua", @"liuyan", @"liaotian-2"];
        NSArray *titles = @[@"免费电话", @"获取资料", @"在线聊天"];
        for (int i = 0; i < titles.count; i++) {
            LPButton *btn = [[LPButton alloc] init];
            btn.style = LPButtonStyleTop;
            btn.frame =CGRectMake(i * (kWindowW / 3), 0, kWindowW / 3, 48);
            btn.space = 5;
            [btn setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:11];
            if (i == 0) {
                [btn setTitleColor:RGBOF(0x666666) forState:UIControlStateNormal];
                [btn setBackgroundColor:[UIColor whiteColor]];
            }else if (i == 1){
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [btn setBackgroundColor:RGBOF(0xF96767)];
            }else{
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
                [btn setBackgroundColor:RGBOF(0xFAB55B)];

            }
            btn.tag = i;
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [contrainerView addSubview:btn];
        }
    }
    return _bottomView;
}

- (void)btnClick:(UIButton *)sender{
    if (sender.tag == 0) {
        //免费电话
        NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"CYProjectDetail_PhonePop1View" owner:self options:nil];
        CYProjectDetail_PhonePop1View *backView = [nibView objectAtIndex:0];
        backView.frame = CGRectMake(0, 0, kWindowW, kWindowH);
        backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        __weak typeof(self)weakself = self;
        backView.block = ^(NSString * _Nonnull phone) {
            [weakself DianHuaWithPhone:phone];
        };
        [backView show];
    }else if (sender.tag == 1){
        //获取资料
        NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"CYProjectDetail_PhonePopView" owner:self options:nil];
        CYProjectDetail_PhonePopView *backView = [nibView objectAtIndex:0];
        self.ziliaoView = backView;
        backView.frame = CGRectMake(0, 0, kWindowW, kWindowH);
        backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        __weak typeof(self)weakself = self;
        backView.block = ^(NSString * _Nonnull name, NSString * _Nonnull phone, NSString * _Nonnull remark) {
            NSLog(@"name -- %@",name);
            [weakself LiuYanWithName:name Phone:phone Remark:remark];
        };
        [backView show];
    }else{
        //在线聊天
        CYChatViewController *chat = [[CYChatViewController alloc] init];
        chat.url = [NSString stringWithFormat:@"%@?device=ios",self.detailModel.wsurl];
        [[AppDelegate sharedAppDelegate] pushViewController:chat];
    }
}

#pragma mark - UIKeyboardNotification

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    __block CGFloat y = kWindowH - CGRectGetMaxY(self.ziliaoView.backView.frame) + 50 - endRect.size.height;
    __weak typeof(self)weakself = self;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        if (y < 0) {
            weakself.ziliaoView.y = y;
        }
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    __weak typeof(self)weakself = self;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        weakself.ziliaoView.y = kWindowH - weakself.ziliaoView.height;
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (void)LiuYanWithName:(NSString *)name Phone:(NSString *)phone Remark:(NSString *)remark{
    if (name.length == 0) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"请填写您的姓名" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if (phone.length == 0) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"请填写您的手机号" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if (remark.length == 0) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"留言不能为空" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    [EasyShowLodingView showLoding];
    __weak typeof(self)weakself = self;
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"guest-book/create"];
    NSDictionary *param = @{@"id":self.detailModel.ID, @"type":@"3", @"truename":name, @"mobile":phone, @"content":remark, @"gfrom":@"14"};
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"留言板 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            //            [self.view makeToast:ResErrorMessage];
            
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [weakself.ziliaoView dismiss];
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[@"message"] duration:1.5 position:CSToastPositionCenter];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[@"message"] duration:1.5 position:CSToastPositionCenter];

            }
        }
    }];
}


- (void)DianHuaWithPhone:(NSString *)phone{
//    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    [EasyShowLodingView showLoding];
    NSDictionary *param = @{@"itemid":self.detailModel.ID, @"callee":phone, @"referrer":@"app", @"gform":@14};
    //将图片上传到服务器
    NSString *urlString = [Api_HOST stringByAppendingString:@"call-phone/create"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    //接收类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    [manager POST:urlString parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [EasyShowLodingView hidenLoding];

        NSLog(@"responseObject--- %@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *responseResult = (NSDictionary *)responseObject;
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[@"message"] duration:1.5 position:CSToastPositionCenter];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[@"message"] duration:1.5 position:CSToastPositionCenter];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error -- %@",error);
        [EasyShowLodingView hidenLoding];

    }];
}

#pragma mark - 获取当前网络状态

/**
 
 *  获取当前网络状态
 
 *
 
 *  0:无网络 & 1:2G & 2:3G & 3:4G & 5:WIFI
 
 */

- (NSString *)getCurrentNetworkState {
    
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"WIFI";
    switch (internetStatus) {
        case ReachableViaWiFi:
            net = @"WIFI";
            break;
            
        case ReachableViaWWAN:
            net = @"蜂窝数据";
            //net = [self getNetType ];   //判断具体类型
            break;
            
        case NotReachable:
            net = @"当前无网路连接";
            
        default:
            break;
    }
    
    return net;
    
}

- (UIImageView *)coverImageView{
    if (!_coverImageView) {
        _coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowW*9/16)];
    }
    return _coverImageView;
}

@end
